package com.myz.app.shiro.realms;


import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

/**
 * 认证
 * @author maoyz on 17-10-9.
 */
public class MyRealm extends AuthenticatingRealm {

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 1 仅支持UsernamePasswordToken类型的Token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 2 取出username
        String username = (String) token.getPrincipal();
        // 3 调用数据库，从中取出username对应信息
        String sqlUsername = "myz";
        // 4 判断账户
        if ("unknown".equals(username)) {
            // 4.1 账户不存在
            throw new UnknownAccountException("账户不存在");
        }
        // 4.2 账户被锁定
        if ("locked".equals(username)) {
            throw new LockedAccountException("账户被锁定");
        }
        // 5 如果身份认证验证成功，返回一个AuthenticationInfo实现,通常使用SimpleAuthenticationInfo；
        Object principal = username;
        Object credentials = null;
        if ("admin".equals(username)){
            // 盐值加密后的值new SimpleHash()
            credentials = new SimpleHash("MD5","123456",ByteSource.Util.bytes(username),1024);
        }
        if ("user".equals(username)){
            credentials = new SimpleHash("MD5","123456",ByteSource.Util.bytes(username),1024);
        }
        // 盐值算法ByteSource.Util.bytes()
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        String realmName = getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName);
        return info;
    }
}
